package cn.tedu.micro.demo.order.service.imp;

import cn.tedu.micro.demo.common.protocol.JsonResult;
import cn.tedu.micro.demo.common.vo.GunInfoVO;
import cn.tedu.micro.demo.order.Order;
import cn.tedu.micro.demo.order.client.DeviceClient;
import cn.tedu.micro.demo.order.dao.repository.OrderRepository;
import cn.tedu.micro.demo.order.po.OrderInfoPO;
import cn.tedu.micro.demo.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private DeviceClient deviceClient;

    @Override
    public String saveOrder(Integer userId, Integer gunId) {
        log.info("当前业务中deviceClient实现类名称:{}",deviceClient.getClass().getName());
        //1.根据枪id查询枪状态,状态不正常,直接异常结束
        checkGunStatus(gunId);
        //2.生成一个全局唯一的字符串编码作为订单编号使用 389erke3f32f29f23fj239r23329f
        String billId=UUID.randomUUID().toString().replace("-","");
        //3.封装OrderInfoPO
        OrderInfoPO poParam=new OrderInfoPO();
        poParam.setUserId(userId);
        poParam.setBillId(billId);
        poParam.setGunId(gunId);
        Date now=new Date();//当前系统时间
        poParam.setCreateTime(now);
        poParam.setUpdateTime(now);
        orderRepository.saveOrder(poParam);
        return billId;
    }

    private void checkGunStatus(Integer gunId) {
        log.info("查询枪的状态,判断可用,gunId:{}",gunId);
        //1.调用查询枪数据
        JsonResult<GunInfoVO> result = deviceClient.getGunStatus(gunId);
        //2.如果code!=0 有问题的 code=0 gunInfoVO=null 有问题
        /*if (result.getCode()==0){
            if (result.getData()!=null) {
                GunInfoVO data = result.getData();
                    if (data.getStatus() == 1) {
                        log.info("枪状态没问题");
                        return ;
                        }
                    }
                }
            {
        }*/
        //其他所有情况
        /*throw new RuntimeException("查询枪状态有问题");*/
        //上述案例逻辑 改成标准断言的格式 如果满足某种条件 则抛异常
        if (result.getCode()!=0||result.getData()==null||result.getData().getStatus()!=1){
            throw new RuntimeException("查询枪状态有问题");
        }
    }
}
